<?
	include_once("sombraGmailer.php");

	if($_POST['command']){

		/* If there old data, we load it before, it must match the cookie user and the IP, maybe not enought */
		$_COOKIE['gmailerUser'] = preg_replace("/[^a-zA-Z0-9\.,_ @|^\-]*/","",$_COOKIE['gmailerUser']);
		session_start();$gmailerUserPath = "users/".$_SERVER['REMOTE_ADDR'].$_COOKIE['PHPSESSID']."/".$_COOKIE['gmailerUser'].".php";
		if(!empty($_COOKIE['gmailerUser']) && file_exists($gmailerUserPath)){$gmailData = curlLoadData($gmailerUserPath);$gmailData['box'] = array();}

		/* If we cant start a new sesion, better redirect to login */
		if(empty($gmailData) && $_POST['command']!="connect"){setcookie("gmailerUser","",-1);echo json_encode(array("errorCode"=>1,"errorDescription"=>"Redirect to login.".$gmailerUserPath,"file"=>__FILE__,"line"=>__LINE__));exit;}

		if(!is_writable("./")){echo json_encode(array("errorCode"=>2,"errorDescription"=>"Write permissions in the base folder needed.","file"=>__FILE__,"line"=>__LINE__));exit;}
		if(!file_exists("users")){mkdir("users");}
		if(!file_exists("users/".$_SERVER['REMOTE_ADDR'].$_COOKIE['PHPSESSID'])){mkdir("users/".$_SERVER['REMOTE_ADDR'].$_COOKIE['PHPSESSID']);}

		header("Content-type: text/json");
		switch($_POST['command']){
			case "connect":
				if(empty($_POST['account']) || empty($_POST['password'])){echo json_encode(array("errorCode"=>1,"errorDescription"=>"Empty params when attepmt to login.","file"=>__FILE__,"line"=>__LINE__));exit;}
				$gmailData = array("account"=>$_POST['account'],"password"=>$_POST['password'],"conected"=>false);
				setcookie("gmailerUser",$gmailData['account'],time()+360000);
				$gmailData = connect($gmailData);

				if(!$gmailData["connected"]){echo json_encode($gmailData['currentStatus']);exit;}
				echo json_encode(array("errorCode"=>"0","data"=>array("box"=>$gmailData['box'],"label"=>$gmailData['label'],"pager"=>$gmailData['pager'])));
				/* The gmailerUser cookie has just been set, the $gmailerUserPath refer to an unnamed .php file on this moment */
				$gmailerUserPath = preg_replace("/\.php$/",$gmailData['account'].".php",$gmailerUserPath);
				curlSaveData($gmailData,$gmailerUserPath);
				break;
			case "getInbox":
				if(empty($_POST['boxType'])){exit;}

				$_POST['boxType'] = strtoupper($_POST['boxType']);
				if(!in_array($_POST['boxType'],array("INBOX","STARRED","SENTMAIL","DRAFTS","ALLMAIL","SPAM","TRASH","LABEL"))){exit;}
				if($_POST['boxType']=="LABEL" && empty($_POST['label'])){exit;}
				$gmailData = getInbox($gmailData,$_POST['boxType'],$_POST['st'],urlencode($_POST['label']));

				if(!$gmailData["connected"]){echo json_encode($gmailData['currentStatus']);exit;}
				echo json_encode(array("errorCode"=>"0","data"=>array("box"=>$gmailData['box'],"label"=>$gmailData['label'],"pager"=>$gmailData['pager'])));
				curlSaveData($gmailData,$gmailerUserPath);
				break;
			case "boxAction":
				if(empty($_POST['boxId'])){echo json_encode(array("errorCode"=>"1","errorDescription"=>"empty boxIDs"));break;}

				$_POST['boxAction'] = strtoupper($_POST['boxAction']);
				if(!in_array($_POST['boxAction'],array("MARKASREAD","MARKASUNREAD","ADDSTAR","REMOVESTAR","MUTE","APPLYLABEL","REMOVELABEL","ARCHIVE","REPORTSPAM","DELETE"))){exit;}
				if(($_POST['boxAction']=="APPLYLABEL" || $_POST['boxAction']=="REMOVELABEL") && $_POST['label']==""){exit;}

				$gmailData = boxAction($gmailData,$_POST['boxAction'],$_POST['boxId'],$_POST['label']);

				//echo exportData($gmailData,array("box","label","pager"));
				echo json_encode(array("errorCode"=>"0","data"=>array("box"=>$gmailData['box'],"label"=>$gmailData['label'],"pager"=>$gmailData['pager'])));
				curlSaveData($gmailData,$gmailerUserPath);
				break;
			case "openBox":
				if($_POST['boxId']==""){exit;}
				$gmailData = openBox($gmailData,$_POST['boxId']);

				echo json_encode(array("errorCode"=>"0","data"=>array("boxOpened"=>$gmailData['boxOpened'],"label"=>$gmailData['label'])));
				curlSaveData($gmailData,$gmailerUserPath);
				break;
			case "sendMail":
				//FIXME: deprecated
				//sendMail($to,$subject,$body,$gmailData,$CC,$CCO,$repliedBoxId,$attachments);
				break;
			case "signOut":
				if($_COOKIE['gmailerUser'] && file_exists($gmailerUserPath)){unlink($gmailerUserPath);}

				setcookie("gmailerUser","",-1);
				echo json_encode(array("errorCode"=>"0"));
				break;
		}
		exit;
	}else if($_GET['command']=="getAttachment"){
		if($_COOKIE['gmailerUser'] && file_exists("users/".$_SERVER['REMOTE_ADDR']."/".$_COOKIE['gmailerUser'].".php")){
			$gmailData = curlLoadData("users/".$_SERVER['REMOTE_ADDR']."/".$_COOKIE['gmailerUser'].".php");
		}else{
			exit;
		}

		if($_GET['fileType']==""){$_GET['fileType']="application/octet-stream";}
		if($_GET['disp']==""){$_GET['disp']="attd";}
		if($_GET['view']==""){$_GET['view']="att";}
		if($_GET['fileName']==""){$_GET['fileName']="genericFilename";}
		if($_GET['th']){$_GET['boxId']=$_GET['th'];}

		$code = getAttachment($_GET['boxId'],$_GET['attid'],$gmailData,$_GET['disp'],$_GET['view']);
		/*little MAGIC NUMBERS*/
		if(substr($code,1,3)=="PNG"){$_GET['fileType']="image/png";}

		header('Content-Disposition: attachment; filename="'.$_GET['fileName'].'"');
		header('Accept-Ranges: bytes');
		header('Content-Length: '.strlen($code));
		header('Content-Type: '.$_GET['fileType']);
		echo $code;
	}else{
		echo "TEST\n";
		$gmailData = array("conected"=>false,"account"=>"","password"=>"");
		$gmailData = connect($gmailData);
		$gmailData = getInbox($gmailData,"LABEL","","Procesados");
		/* Now we take the first box and move it to the thrash*/
		//$box = $gmailData['box'][0];
		//$gmailData = boxAction($gmailData,"DELETE",$box['boxId']);
		/* Taking another one */
		$box = $gmailData['box'][0];
		$gmailData = openBox($gmailData,$box['boxId']);
		
		
		print_r($gmailData);
		exit;
		//*/
	}
?>
